<script setup lang="ts">
import Header from '@/components/Header.vue'
import Menu from '@/components/Menu.vue'
import MyBox from '@/components/MyBox.vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { Query,Operate } from '@/api'
import { useMessage } from '@/hooks/useMessage'
import SeamlessList from "@/views/KB-LG/components/SeamlessList.vue";
import RatioChart from "@/views/KB-LG/components/RatioChart.vue";
import YieldChart from "@/views/KB-LG/components/YieldChart.vue";
const currentEnv = import.meta.env.DEV
const baseURL = window.location.origin
const { query } = useRoute()
type lineInfo = {
  CT: string
  FPY: string
  FPYStatus: string
  Line: string
  LineState: string
  Name: string
  RunStatus: string
  Shift: string
}
type deviceInfo = {
  Brand: string
  CT: string
  Name: string
  IP: string
  ImageName: string
  Number: string
  Port: string
  RValue: string
  SensorStatus: string
  Seq: string
  Status: string
  UseStatus: string
  deviceDetail: boolean,
}
//看板标题
const title = ref('')
const lineListInfo = ref({
  CT: "",
  FPY: "",
  FPYStatus: "",
  Line: "",
  LineState: "",
  Name: "",
  RunStatus: "false",
  FARunStatus: "false",
  TestRunStatus: "false",
  Shift: "",
})
const lineFieldList = ref<lineInfo[]>([])
//折线图
const yieldChartInfo = ref({
  legendList: [],
  timeList: [],
  targetList: [],
  actualList:[],
  max:'',
  min:''
})
const deviceList = ref([])
//设备状态
const statusList = ref([
  {
    label: '离线',
    color: '#BFBFBF'
  },
  {
    label: '待机',
    color: '#F4EA2A'
  },
  {
    label: '运行',
    color: '#1AFA29'
  },
  {
    label: '故障',
    color: '#D81E06'
  },
  {
    label: '急停',
    color: '#E98F36'
  }
])
const statusMap = {
  0: statusList.value[0], // 离线
  1: statusList.value[1], // 待机
  2: statusList.value[2], // 运行
  3: statusList.value[3], // 故障
  4: statusList.value[4]  // 急停
}
const FPYStatusMap = {
  0: statusList.value[3], // 红色
  1: statusList.value[4], // 橙色
  2: statusList.value[2], // 绿色
}
//表格数据
const tableData1 = ref<any[]>([])
const tableData2 = ref<any[]>([])
const tableData3 = ref<any[]>([])
const cols1 = ref<any[]>([])
const cols2 = ref<any[]>([])
const cols3 = ref<any[]>([])
//设备图片
const imageList = ref<deviceInfo[]>([])
//图表数据
const chartInfo = ref({
  legendList: [],
  timeList: [],
  planList: [],
  actualList: []
})
//刷新周期
const flushTimer = ref()
//底部责任人
const otherInfo = ref({
  PD: '',
  QA: '',
  PE: ''
})

//线别
const line = ref('')
const lineList = ref()
const statusInfoList = ref([])
//站别
const station = ref('')
const stationList = ref()
//切换线别
const saveCT = async () => {
  //获取站别信息
  const res = (await Operate({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Operate;$;Oper=SaveLineCT`,
    jsonData: [{
      CT: lineListInfo.value.CT
    }]
  })) as any
  if (res.code!== 200) {
    message.error(res.msg)
    return
  } else {
    message.success(res.msg)
  }
}

const saveRunStatus = async (type:any) => {
  //获取站别信息
  const res = (await Operate({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Operate;$;Oper=Save${type}`,
    jsonData: [{
      [type]: lineListInfo.value[type],
    }]
  })) as any
  if (res.code!== 200) {
    message.error(res.msg)
    return
  } else {
    message.success(res.msg)
  }
}

//获取表格和图表数据
const getKBInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=GetKBInfo;$;Key=Station;$;Line=${line.value};$;Station=${station.value}`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const {rValueInfo, lineInfo,deviceInfo,statusInfo,errInfo,topErrInfo } = res.data
  tableData1.value = errInfo || []
  tableData2.value = topErrInfo || []
  // tableData3.value = topAlarmInfo || []
  //占比
  // rationChartInfo.value.list =
  //     statusInfo.map((item: any) => {
  //       return {
  //         value: item.Qty,
  //         name: statusMap[item.Number].label
  //       }
  //     }) || []
  statusInfoList.value = statusInfo || []
  imageList.value = deviceInfo.map((item:any) =>{
    return {
      ...item,
      deviceDetail: ref(false)
    }
  }) || []
  title.value = lineInfo[0].Name
  lineListInfo.value = lineInfo[0]
  yieldChartInfo.value.timeList = rValueInfo.map((item: any) => item.Number)
  yieldChartInfo.value.actualList = rValueInfo.map((item: any) => item.RValue)
  yieldChartInfo.value.max = parseInt(rValueInfo[0].UpValue)
  yieldChartInfo.value.min = parseInt(rValueInfo[0].LowValue)

  // yieldChartInfo.value.targetList = rValueInfo.map((item: any) => item.TargetFPY)
}
//切换站别
const changeStation = async () => {
  // 先关闭定时器再重新启动刷新周期
  stopTimer()
  //选择站别之后，开始循环获取数据GetKBInfo
  startTimer()
}

const message = useMessage()
//获取页面信息
const getPageInfo = async () => {
  const res = (await Query({
    inputStr: `GroupName=${query.groupName};$;JobType=${query.jobType};$;OperType=Getpage`
  })) as any
  if (res.code !== 200) {
    message.error(res.msg)
    return
  }
  const { deviceFieldInfo, statusFieldInfo,lineInfo, lineFieldInfo,errFieldInfo,topErrFieldInfo } = res.data
  cols1.value = errFieldInfo || []
  cols2.value = topErrFieldInfo || []
  // cols3.value = topAlarmFieldInfo || []
  deviceList.value = deviceFieldInfo || []
  flushTimer.value = lineInfo.length && lineInfo[0].RefCT
  console.log(flushTimer.value)
  lineFieldList.value = lineFieldInfo.filter((item:any) => ['Name', 'FPYStatus','RefCT'].indexOf(item.value) == -1) || []
}

// 1.循环过程中，重新选择【线别】，关闭循环，选定【站别】后重新开始
// 2.循环过程中，重新选择【站别】，关闭循环并开始新循环

// 定义状态
const isRunning = ref(false)
const timerId = ref<number | null>(null)

// 开始定时器
const startTimer = async () => {
  if (isRunning.value) return // 防止重复启动

  isRunning.value = true
  console.log('定时器启动')

  // 立即执行一次
  await getKBInfo()

  // 设置定时器，每3分钟执行一次 (3分钟 = 3*60*1000 = 180000毫秒)
  const timer = flushTimer.value ?  flushTimer.value * 1000 : 10000
  console.log(timer)
  timerId.value = window.setInterval(getKBInfo, timer)
}

// 停止定时器
const stopTimer = () => {
  if (timerId.value) {
    window.clearInterval(timerId.value)
    timerId.value = null
    isRunning.value = false
    console.log('定时器已停止')
  }
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopTimer()
})
//设备状态统计
const rationChartInfo = ref({
  list: []
})
const showOverlay = (item:any) => {
  item.deviceDetail = !item.deviceDetail
}
const getImageUrl = (list: any) => {
  return new URL(`/src/assets/deviceImages/${list.ImageName}.png`, import.meta.url).href
}

onMounted(async() =>{
  await getPageInfo()
  // getKBInfo()
  await startTimer()
})
</script>
<template>
  <div class="w-full overflow-hidden my-page">
    <Header :title="title" />
    <section class="board-content">
      <div class="flex justify-between other-info">
        <MyBox title="" style="width: 100%;">
          <template v-slot:main>
            <div class="flex items-center justify-between">
              <p v-if="lineFieldList.length > 0 " class="run-info" v-for="(i,index) in lineFieldList" :key="index">
                <label>{{i.label}}：</label>
                <span v-if="i.value == 'CT'">
                  <el-input-number class="my-input-number" v-model="lineListInfo.CT" />
                  <el-button size="large" class="custom-btn" style="margin-left: 20px" type="primary" @click="saveCT">保存</el-button>
                </span>
                <span v-else-if="i.value == 'FARunStatus'">
                  <el-switch
                      @change="saveRunStatus('FARunStatus')"
                      name="runStatus"
                      v-model="lineListInfo.FARunStatus"
                      active-value="true"
                      inactive-value="false"
                      size="large"
                      class="large-switch"
                      style="--el-switch-on-color: #3F7EFA; --el-switch-off-color: #ff4949;"
                  />
                </span>
                <span v-else-if="i.value == 'TestRunStatus'">
                  <el-switch
                      @change="saveRunStatus('TestRunStatus')"
                      name="runStatus"
                      v-model="lineListInfo.TestRunStatus"
                      active-value="true"
                      inactive-value="false"
                      size="large"
                      class="large-switch"
                      style="--el-switch-on-color: #3F7EFA; --el-switch-off-color: #ff4949;"
                  />
                </span>
                <span v-else-if="i.value == 'FPY'" :style="{ color: FPYStatusMap[lineListInfo.FPYStatus]?.color}">{{lineListInfo[i.value]}}</span>
                <span v-else>{{lineListInfo[i.value]}}</span>
              </p>
            </div>
          </template>
        </MyBox>
      </div>
      <el-row :gutter="20" class="row">
        <el-col :span="18">
          <MyBox title="设备状态">
            <template v-slot:extra>
              <div class="flex items-center justify-between status-info">
                <p v-for="(item, index) in statusList" :key="index" class="flex items-center">
                <span class="status-color" :style="{ background: item.color }"></span>
                <span class="status-text">{{ item.label }}</span>
                </p>
              </div>
            </template>
            <template v-slot:main>
              <div class="image-list flex flex-wrap">
                <div style="width:5%;margin-top: -18px" class="image-card items-center" v-for="(item, index) in imageList" :key="index">
                  <img
                      @click="showOverlay(item)"
                      v-if="currentEnv"
                      :src="getImageUrl(item)"
                      alt="Image"
                  />
                  <img v-else :src="`${baseURL}/deviceImages/${item.ImageName? item.ImageName : '1-8' }.png`" alt="Local Image" />
                  <div v-show="item.deviceDetail" class="overlay">
                    <p v-for="(i,index) in deviceList" :key="index">
                      {{i.label}}：<span>{{ item[i.value] }}</span>
                    </p>
                    <div class="arrow arrow-left arrow-delay"></div>
                  </div>
                </div>
              </div>
              <div class="flex justify-around yield-list">
                <div class="relative yield-item" v-for="(item, index) in statusInfoList" :key="index">
                  <p class="label" :style="{ color: statusMap[item.Number]?.color}">{{ item.Name }}</p>
                  <p class="text-center value" :style="{ color: statusMap[item.Number]?.color}">
                    {{item.Qty}}
                  </p>
                </div>
              </div>
            </template>
          </MyBox>
          <MyBox
              title="设备阻值"
              style="width: 100%;margin-top: 15px"
          >
            <template v-slot:main>
<!--              <RatioChart :data="rationChartInfo" />-->
              <YieldChart :data="yieldChartInfo" />
            </template>
          </MyBox>
        </el-col>

        <el-col :span="6">
          <MyBox title="异常信息" style="width: 100%;padding: 15px 15px 0 15px;">
            <template v-slot:main>
              <div class="container-scroll" style="margin-top: 10px;height:390px;overflow-y: scroll"><SeamlessList :data="tableData1" :cols="cols1" /></div>
            </template>
          </MyBox>
          <MyBox title="故障信息(TOP10)" style="width: 100%;margin-top: 15px;padding: 15px 15px 0 15px;">
            <template v-slot:main>
              <div style="margin-top: 10px;height:390px"><SeamlessList :data="tableData2" :cols="cols2" /></div>
            </template>
          </MyBox>
<!--          <MyBox title="急障信息(TOP10)" style="width: 100%">-->
<!--            <template v-slot:main>-->
<!--              <div style="margin-top: 20px"><SeamlessList :data="tableData2" :cols="cols2" /></div>-->
<!--            </template>-->
<!--          </MyBox>-->
        </el-col>

      </el-row>
    </section>
    <Menu />
  </div>
</template>
<style lang="less" scoped>
.large-switch.is-checked{
  :deep(.el-switch__core){
    .el-switch__action{
      left: calc(100% - 34px)!important;
    }
  }
}
.large-switch {
  :deep(.el-switch__core) {
    height: 36px;
    min-width: 80px;
    border-radius: 20px;
    .el-switch__action{
      width: 34px;
      height: 34px;
    }
    &::after {
      width: 34px;
      height: 34px;
    }
  }

  :deep(.el-switch__inner) {
    font-size: 16px;
  }
}
.container-scroll {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}
.container-scroll::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}
:deep(.custom-btn) {
  font-size: 20px;
}
:deep(.el-button--large) {
  font-size: 20px;
}

.row {
  margin: 15px auto;
}
.extra {
  position: absolute;
  right: 30px;
  top: 10px;
  font-size: 22px;
  color: #8fe1ff;
  .select-box {
    margin-right: 20px;
  }
  p {
    padding-left: 10px;
    &:before {
      display: inline-block;
      content: '';
      width: 18px;
      height: 18px;
      margin-right: 10px;
      background: #00b8a9;
      border-radius: 2px;
    }
    &:first-child {
      &::before {
        background: #f7c873;
        border-radius: 50%;
      }
    }
  }
}

.other-info {
  color: #8fe1ff;
  font-size: 24px;
  margin-top: 20px;
  .flex {
    width: 98%;
    margin: 0 auto;
  }
}
.el-select-dropdown__item {
  font-size: 18px;
}

.status-info {
  p {
    margin-left: 26px;
  }
  position: absolute;
  right: 28px;
  top: 15px;
  .status-color {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin-right: 8px;
  }
  .status-text {
    font-size: 20px;
    color: #8fe1ff;
  }
}

.image-list {
  width: 100%;
  margin: 30px 0 0 0;
}
.image-card {
  position: relative;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
  cursor: pointer;
  //&:hover .overlay {
  //  opacity: 1;
  //  z-index: 10000;
  //  .arrow {
  //    opacity: 1;
  //  }
  //}
  .overlay {
    position: absolute;
    top: -10px;
    left: 50px;
    width: 251px;
    height:365px;
    padding: 10px;
    //opacity: 0;
    transition: opacity 0.4s ease;
    border: 2px solid #00aeff;
    background: #040d4c;
    z-index: 9999;
    /* 左侧箭头 */
    .arrow {
      position: absolute;
      width: 0;
      height: 0;
      border-style: solid;
      transition: all 0.4s ease;
    }
    .arrow-left {
      top: 12%;
      left: -15px;
      transform: translateY(-50%);
      border-width: 15px 15px 15px 0;
      border-color: transparent rgba(46, 152, 201, 1) transparent transparent;
    }
    h3 {
      color: white;
      border: 2px solid #00aeff;
      span {
        display: inline-block;
        float: right;
      }
      margin-bottom: 5px;
    }
    p {
      color: white;
      span {
        display: inline-block;
        float: right;
      }
      margin-bottom: 5px;
    }
  }
}
.run-info{
  margin-left: 10px;
  margin-right: 20px;
  label{
    color:#fff;
    //margin-right: 15px;
    font-size: 24px;
  }
  span{
    color: #00f2f1;
    font-size: 24px;
  }
    .my-input-number{
      width: 138px;
      height: 36px;
    }
    :deep(.my-input-number .el-input__wrapper){
      height: 36px;
    }
    :deep(.my-input-number .el-input-number__decrease){
      background: inherit;
      color: #00AEFF;
      font-size: 16px;
      font-weight: 700;
      border-right: 1px solid #00AEFF;
    }
    :deep(.my-input-number .el-input-number__increase){
      background: inherit;
      color: #00AEFF;
      font-size: 16px;
      font-weight: 700;
      border-left: 1px solid #00AEFF;
    }

}
.yield-list {
  background: rgba(18, 155, 255, 0.2);
  padding: 16px 0 10px;
  .yield-item{
    width: 100%;
  }
  .yield-item:not(:last-child) {
    &::after {
      display: block;
      content: '';
      width: 2px;
      height: 54px;
      background: url('@/assets/wo-line.png') no-repeat center center;
      position: absolute;
      top: 14px;
      right: 0;
    }
  }
  .label {
    font-size: 24px;
    color: #fff;
    text-align: center;
  }
  .value {
    height: 42px;
    font-size: 24px;
    color: #2e95f8;
  }
}
</style>
